import React, { useEffect, useState } from 'react';
import { Image } from '@tarojs/components';
import { sourceUrl } from '@/config';

const pProDef = `https://ht-finesdk.oss-cn-beijing.aliyuncs.com/weapp/taihujishi/media/proDef.png`;
const pShopDef = `https://ht-finesdk.oss-cn-beijing.aliyuncs.com/weapp/taihujishi/media/shopDef.png`;
const pShopPhotoDef = `https://ht-finesdk.oss-cn-beijing.aliyuncs.com/weapp/taihujishi/media/shopPhotoDef.png`;
const pIndustryDefault = `https://ht-finesdk.oss-cn-beijing.aliyuncs.com/weapp/taihujishi/media/industryDefault.png`;

const getSrcByType = (type) => {
  let theSrc = pProDef;
  switch (type) {
    case 'shop':
      theSrc = pShopDef;
      break;
    case 'product':
      theSrc = pProDef;
      break;
    case 'shopPhoto':
      theSrc = pShopPhotoDef;
      break;
    case 'secondIndustry':
      theSrc = pIndustryDefault;
      break;
    default:
      break;
  }
  return theSrc;
};

const initSrc = (src, type) => {
  if (src == '') {
    return getSrcByType(type);
  } else {
    return src.indexOf('http') === 0 ? src : sourceUrl + src;
  }
};

const Imagelocation = ({ className, src = '', onClick = null, type = 'product' }) => {
  const [curSrc, setCurSrc] = useState(initSrc(src, type));

  const handleImgError = () => {
    let theSrc = getSrcByType(type);
    setCurSrc(theSrc);
  };

  useEffect(() => {
    setCurSrc(initSrc(src, type));
  }, [src]);

  return <Image className={className} src={curSrc} onClick={onClick} onError={handleImgError} />;
};

export default Imagelocation;
